const fs = require('fs');

let path = "../../ggameProtocol/"
var outPutFile = '../../assets/script/tscript/protobuf/ProtoIDEnum.ts';

if(process.argv.length>2)
{
    if(process.argv.length>2){
        path = `${__dirname}/${process.argv[2]}`;
    }
    if(process.argv.length>3){
        outPutFile = `${__dirname}/${process.argv[3]}`;
    }
}

let proto = new Map();

function readFiles(path) {
    let files = fs.readdirSync(path);
    files.forEach(function (itm) {
        let fileUrl = path + '/' + itm;
        let stat = fs.statSync(fileUrl);
        if (stat.isDirectory()) {
            readFiles(fileUrl); // 递归遍历文件夹
        } else {
            if (fileUrl.indexOf(".proto") >= 0) {
                // console.log(`proto文件：${fileUrl}`);
                readProto(fileUrl);
            }
        }
    });
}
readFiles(path)

function readProto(fileUrl){
	let dataTmp = fs.readFileSync(fileUrl, 'utf8')
	let tag = "";
	let lines = dataTmp.toString().split("\n");

	lines.forEach((line)=>{
		let priority = 1;
		const regex = /(message SC|message GC|message BC)/;// /(message SC|message GC|message TC|message BC)/
    	const match = line.match(regex);
		let indexTmp = match ? match.index : -1 ;
		if(indexTmp < 0){
			indexTmp = line.indexOf("message CS");
			priority = 2;
		}
		if(indexTmp >= 0){
			// console.log(`${line}`)
			let strTmp = line.substr(indexTmp + 10);
			let strTmps = strTmp.split("_")
			let protoId = strTmps[0];
			
			strTmp = strTmps[1].split(" ")[0];
			if(priority === 1 || !proto.get(protoId)){
				proto.set(Number(protoId), `${strTmp}__${tag}`);
				console.log(`protoId-${protoId}`)
				console.log(`strTmp-${strTmp}`)
				console.log(`tag-${tag}`)
			}
		}else{
			tag = line.trim();
		}
	})
}

let protoIds = Array.from(proto.keys()).sort((a,b)=>{
	return a - b;
});

let outStr = "";
outStr += "/*\n";
outStr += "* 自动生成，不要手动修改;\n";
outStr += "*/\n";
outStr += "export class ProtoIDEnum {\n";
for(let item of protoIds){  
	console.log("tag="+proto.get(item))
	let tags = proto.get(item).split("__");
	outStr += `    public static ${tags[0]}: number = ${item};${tags[1]}\n`;
}
outStr+="}";
console.log(outStr);
	
fs.writeFile(outPutFile, outStr, {encoding:'utf8'}, function(err) {
	if(!err){
		console.log("成功！")
	}else{
		console.log("失败!");
		console.log(err);
	}
});